﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using Anywhere.Common;
using System.ComponentModel.Composition;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;

namespace MainApp
{
    public delegate void PluginChangeEventhandle();

    public static class CompositionHelper
    {
        public static CompositionContainer Container;

        static bool isLoaded = false;

        public static event PluginChangeEventhandle PluginChanged;

        public static void Init(Assembly[] assemblies, App app)
        {
            if (isLoaded) return;
            if (assemblies.IsNull()) return;

            var catalogs = assemblies.Select(o => new AssemblyCatalog(o)).ToArray();
            var aggregateCatalog = new AggregateCatalog(catalogs);
            Container = new CompositionContainer(aggregateCatalog);
            Container.ComposeParts(app);
            isLoaded = true;
        }

        public static void LoadPlugin()
        {
            var pluginPath = AppDomain.CurrentDomain.BaseDirectory + @"Plugin";
            if (!Directory.Exists(pluginPath)) return;
            DirectoryCatalog directoryCatalog = new DirectoryCatalog(pluginPath);
            var currentCatalogs = (AggregateCatalog)CompositionHelper.Container.Catalog;
            currentCatalogs.Catalogs.Add(directoryCatalog);

            if (PluginChanged != null)
                PluginChanged();
        }
    }
}
